<template>
  <div ref="lyricContainerRef" class="lyric-list ">
    <el-scrollbar ref="scrollbarRef" height="100%">
      <ul v-if="showLyric" class="lyric-ul " ref="lyricRef"></ul>
    </el-scrollbar>

  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, nextTick, onUnmounted, WatchStopHandle } from "vue"
import { useAudio } from "@/utils/useAudio"
const {

  audioRef,
  currentLyric

} = useAudio()

function parseLyric(ly: string) {
  const lyArr = ly.split('\n')
  const result = lyArr.map(item => {
    const wordArr = item.split('\]')

    let time = parseTime(wordArr[0].substring(1))
    let word = wordArr[1] == "" ? wordArr[0].split(":")[1] : wordArr[1]
    return {
      time,
      word
    }
  })
  return result

}

// 01:05.51
function parseTime(time: string) {
  const timeArr = time.split(':')
  const ti = parseInt(timeArr[0]) * 60 + parseInt(timeArr[1])
  return isNaN(ti) ? 0 : ti
}
const showLyric = ref(true)
const lyricList = ref<{ time: number, word: string }[]>([])
watch(currentLyric, lyric => {
  lyricList.value = parseLyric(lyric)
  console.log('歌词变了', lyric)
  reCreateLyric()
})
setTimeout(() => {
  currentLyric.value = currentLyric.value + ' ';
}, 100);

// 重新渲染歌词
const reCreateLyric = () => {
  showLyric.value = false
  nextTick(() => {
    showLyric.value = true
    setTimeout(() => {
      createLrcElement()
    })
  })
}


// 找到需要高亮歌词
function findIndex() {
  for (let i = 0; i < lyricList.value.length; i++) {
    if (lyricList.value[i].time > audioRef.value.currentTime) {
      return i - 1;
    }
  }
  // 没有找到说明播放完毕
  return lyricList.value.length - 1
}

// 歌词容器
const lyricContainerRef = ref<HTMLElement>()
// 歌词元素
const lyricRef = ref<HTMLElement>()
const currentFrag = ref(document.createDocumentFragment())
// 创建元素
function createLrcElement() {
  currentFrag.value = document.createDocumentFragment()
  for (let i = 0; i < lyricList.value.length; i++) {
    const li = document.createElement('li')
    li.textContent = lyricList.value[i].word
    currentFrag.value.appendChild(li)
  }
  lyricRef.value?.appendChild(currentFrag.value)
}

const audioRef2 = ref<HTMLAudioElement>()


onMounted(() => {
  createLrcElement()
  audioRef2.value = audioRef.value
})


const scrollbarRef = ref()
// 设置offset
function setOffest() {
  const currentIndex = findIndex();
  const containerHight = (lyricContainerRef.value?.clientHeight ?? 0)
  if (showLyric.value == false && !lyricRef.value && !lyricRef.value.children[0]) return
  let liHight = lyricRef.value?.children[0]?.clientHeight ?? 0
  let maxOffset = (lyricRef.value?.clientHeight ?? 0) - containerHight
  let offset = liHight * currentIndex + liHight / 2 - containerHight / 2

  // 设置最小offset
  if (offset < 0) offset = 0

  // 最大offset
  if (offset > maxOffset) offset = maxOffset
  if (lyricRef.value) {
    lyricRef.value.style.transform = `translateY(-${offset}px)`;
  }
  // 是指active前 消除之前的active
  const li = lyricRef.value?.querySelector('.active')
  li && li.classList.remove('active')
  lyricRef.value?.children[currentIndex]?.classList.add('active')

}

watch(audioRef2, nRef => {
  console.log("获取新的了")
  nextTick(() => {
    nRef.addEventListener('timeupdate', () => {
      try {
        setOffest()
      } catch (error) {
        console.log(error)
      }
    })
  })
})




</script>
<style lang="scss">
.lyric-list {
  width: 30rem;
  height: 11rem;
  background-color: var(--background-gray-color);
  border-radius: 0.5rem;
  pointer-events: none;
}

.lyric-ul {
  list-style: none;
  width: 100%;
  transition: .3s;
  font-size: 0.5rem;
  display: flex;
  flex-direction: column;
  align-items: center;

}

.lyric-ul li {
  height: 30px;
  line-height: 30px;
  transition: .3s;
}

.lyric-ul li.active {
  transform: scale(1.3);
  color: blueviolet;
}
</style>